const { sqlPromise } = require("../db/sqlPromise");
const bcrypt = require("bcryptjs"); //密码加密解密
const jwt = require("jsonwebtoken");
const { secretKey } = require("../config");

//登录
exports.login = async (req, res) => {
  let sql = "select * from sp_user where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (!results.length) return res.send({ status: 100, msg: "用户名不存在" });
  let queryPwd = results[0].password;
  const compareResult = bcrypt.compareSync(req.body.password, queryPwd);
  if (!compareResult) return res.send({ status: 100, msg: "密码错误" });
  let token = jwt.sign({ username: results[0].username }, secretKey, {
    expiresIn: '10h',
  });
  res.send({
    status: 200,
    msg: "登录成功",
    token: "Bearer " + token,
  });
};

//注册
exports.register = async (req, res) => {
  console.log(req.body);

  let sql = "select * from sp_user where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (results.length > 0) return res.send({ status: 100, msg: "用户名已存在" });

  // 密码加密处理
  let serectPwd = bcrypt.hashSync(req.body.password, 10);

  //可选参数 email mobile处理
  let insertArr = [req.body.username, serectPwd];
  let str1 = "username,password";
  let str2 = "?,?";
  if (req.body.email) {
    str2 += ",?";
    str1 += ",user_email";
    insertArr = [...insertArr, req.body.email];
  }
  if (req.body.mobile) {
    str2 += ",?";
    str1 += ",user_tel";
    insertArr = [...insertArr, req.body.mobile];
  }

  let insertSql = `insert into sp_user (${str1}) values (${str2})`;
  let insertRes = await sqlPromise(insertSql, insertArr);
  console.log(insertRes);

  if (insertRes.affectedRows != 1)
    return res.send({ msg: "添加失败 未知错误" });

  let endResults = await sqlPromise(sql, [req.body.username]);

  res.send({
    data: endResults,
    meta: {
      msg: "用户创建成功",
      status: 201,
    },
  });
};

//获取用户列表
exports.getUsers = async (req, res) => {
  let sql = "select * from sp_user";
  let result = await sqlPromise(sql);
  res.send({
    meta: {
      msg: "获取成功",
      status: 200,
    },
    data: {
      users: result,
    },
  });
};

//根据id获取用户信息
exports.getUser = async (req, res) => {
  console.log(req.params);
  let id = req.params.id;
  let sql = "select * from sp_user where user_id = ?";
  let result = await sqlPromise(sql, [id]);
  res.send({
    meta: {
      msg: "获取成功",
      status: 200,
    },
    data: {
      users: result,
    },
  });
};

//更新用户信息
exports.updateUser = async (req, res) => {
  let sql = `UPDATE sp_user SET ? WHERE user_id = ?`;
  let obj = {};
  if (req.query.email) obj["user_email"] = req.query.email;
  if (req.query.mobile) obj["user_tel"] = req.query.mobile;
  console.log(obj);
  let results = await sqlPromise(sql, [obj, req.params.id]);
  if (results.affectedRows != 1)
    return res.send({
      msg: "更新失败",
      status: 100,
    });

  let findSql = "select * from sp_user where user_id = ?";
  let endRes = await sqlPromise(findSql, [req.params.id]);
  console.log(endRes[0]);
  res.send({
    data: {
      id: endRes[0].user_id,
      mobile: endRes[0].user_tel,
      email: endRes[0].user_email,
      role_id: endRes[0].role_id,
    },
    meta: {
      msg: "更新成功",
      status: 200,
    },
  });
};

//删除用户
exports.delUser = async (req, res) => {
  let sql = 'DELETE FROM sp_user WHERE user_id = ?'
  let results = await sqlPromise(sql, [req.params.id]);
  if (results.affectedRows != 1)
    return res.send({
      msg: "删除失败",
      status: 100,
    });

  res.send({
    data: null,
    meta: {
      msg: "删除成功",
      status: 200,
    },
  });
};
